<template>
  <div class="chart-container">
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-date-picker
            v-model="selectedTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 100%;">
          </el-date-picker>
        </el-col>
        <el-col :span="8">
          <el-select v-model="selectedDepartment" filterable placeholder="请选择部门" style="width: 100%;">
            <el-option
              v-for="department in departments"
              :key="department.id"
              :label="department.projectName"
              :value="department.id">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-select v-model="selectedChemicalAgent" filterable placeholder="请选择生化药剂" style="width: 100%;">
            <el-option
              v-for="agent in chemicalAgentsOptions"
              :key="agent.value"
              :label="agent.label"
              :value="agent.value">
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="24" style="text-align: right;">
          <el-button type="primary" @click="handleQuery">查看</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-card class="chart-card">
      <div ref="chart" class="chart"></div>
      <!--      <div class="chart-title">-->
      <!--        <h2>药剂费用与投加浓度</h2>-->
      <!--        <p>Feature Sample: Gradient Color, Shadow, Click Zoom</p>-->
      <!--      </div>-->
    </el-card>
    <el-card v-if="costInfo" class="cost-card">
      <div class="cost-info">
        <h2>药剂费用: {{ costInfo.cost }}</h2>
      </div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { fetchDosageConcentration } from '@/api/count/dosageConcentrationAnalysis';
import { fetchDepartments } from '@/api/count/count';

export default {
  name: 'EchartsBarChart',
  dicts: ['drug_type'],
  data() {
    return {
      myChart: null,
      option: null,
      dataAxis: [],
      costData: [],
      concentrationData: [],
      yMax: 500,
      dataShadow: [],
      departments: [],
      chemicalAgents: [],
      selectedDepartment: '',
      selectedChemicalAgent: '',
      selectedTimeRange: '',
      costInfo: null,
      loading: false
    };
  },
  computed: {
    chemicalAgentsOptions() {
      return this.dict.type.drug_type || [];
    }
  },
  mounted() {
    this.fetchDepartments();
  },
  methods: {
    async fetchDepartments() {
      try {
        const response = await fetchDepartments();
        this.departments = response.data;
      } catch (error) {
        console.error('获取部门数据失败', error);
      }
    },
    async handleQuery() {
      if (!this.selectedDepartment) {
        this.$message.warning('请选择部门');
        return;
      }

      if (!this.selectedTimeRange || this.selectedTimeRange.length !== 2) {
        this.$message.warning('请选择时间段');
        return;
      }

      this.loading = true;
      try {
        const params = {
          departmentId: this.selectedDepartment,
          startDate: this.selectedTimeRange[0],
          endDate: this.selectedTimeRange[1]
        };
        if (this.selectedChemicalAgent) {
          params.chemicalAgentId = this.selectedChemicalAgent;
        }

        const response = await fetchDosageConcentration(params);
        // 格式化 dataAxis 日期
        this.dataAxis = response.data.dataAxis.map(date => date.split(' ')[0]);
        this.costData = response.data.costData;
        this.concentrationData = response.data.concentrationData;
        this.yMax = response.data.yMax;
        this.costInfo = response.data.costInfo;

        this.initChart();
      } catch (error) {
        console.error('查询数据失败', error);
      } finally {
        this.loading = false;
      }
    },
    initChart() {
      // 初始化数据阴影
      this.dataShadow = this.dataAxis.map(() => this.yMax);

      this.option = {
        title: {
          text: '药剂费用与投加浓度',
          subtext: 'Feature Sample: Gradient Color, Shadow, Click Zoom',
          left: 'center',
          top: 'bottom',
          padding: [0, 0, 0, 0]
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['药剂费用', '投加浓度'],
          bottom: '5%'
        },
        xAxis: {
          data: this.dataAxis,
          axisLabel: {
            inside: false,
            color: '#333',
            rotate: 45
          },
          axisTick: {
            show: false
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#ccc'
            }
          },
          z: 10
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: true,
            lineStyle: {
              color: '#ccc'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#999'
          },
          splitLine: {
            lineStyle: {
              color: ['#eee']
            }
          },
          splitNumber: 10
        },
        dataZoom: [
          {
            type: 'inside'
          }
        ],
        series: [
          {
            name: '药剂费用',
            type: 'bar',
            showBackground: true,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ]),
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#2378f7' },
                  { offset: 0.7, color: '#2378f7' },
                  { offset: 1, color: '#83bff6' }
                ]),
                shadowBlur: 20,
                shadowColor: 'rgba(0, 0, 0, 0.7)'
              }
            },
            data: this.costData
          },
          {
            name: '投加浓度',
            type: 'bar',
            showBackground: true,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#ff9999' },
                { offset: 0.5, color: '#ff4d4d' },
                { offset: 1, color: '#ff4d4d' }
              ]),
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  { offset: 0, color: '#ff1a1a' },
                  { offset: 0.7, color: '#ff1a1a' },
                  { offset: 1, color: '#ff9999' }
                ]),
                shadowBlur: 20,
                shadowColor: 'rgba(0, 0, 0, 0.7)'
              }
            },
            data: this.concentrationData
          }
        ]
      };

      const chartDom = this.$refs.chart;
      this.myChart = echarts.init(chartDom);
      this.myChart.setOption(this.option);

      // Enable data zoom when user click bar.
      const zoomSize = 6;
      this.myChart.on('click', (params) => {
        console.log(this.dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)]);
        this.myChart.dispatchAction({
          type: 'dataZoom',
          startValue: this.dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)],
          endValue: this.dataAxis[Math.min(params.dataIndex + zoomSize / 2, this.data.length - 1)]
        });
      });
    }
  }
};
</script>

<style scoped>
.chart-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: linear-gradient(135deg, #f0f8ff, #e6f7ff); /* 更浅的渐变背景色 */
  padding: 40px;
  border-radius: 16px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.filter-card, .chart-card, .cost-card {
  width: 100%;
  max-width: 900px;
  margin-bottom: 40px;
  background: linear-gradient(135deg, #ffffff, #f0f8ff); /* 更浅的渐变背景色 */
  border-radius: 16px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.filter-card {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.el-row {
  margin-bottom: 20px;
}

.el-col {
  margin-bottom: 20px;
}

.chart {
  width: 100%;
  height: 600px;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  background: linear-gradient(135deg, #ffffff, #f0f8ff); /* 更浅的渐变背景色 */
}

.chart-title {
  text-align: center;
  margin-top: 30px;
}

.chart-title h2 {
  margin: 0;
  font-size: 32px;
  color: #333;
}

.chart-title p {
  margin: 5px 0 0;
  font-size: 20px;
  color: #666;
}

.cost-info {
  text-align: center;
  margin-top: 20px;
}

.cost-info h2 {
  margin: 0;
  font-size: 28px;
  color: #333;
}

.el-button--primary {
  background: linear-gradient(135deg, #409EFF, #66b1ff); /* 更协调的渐变按钮颜色 */
  border-color: #409EFF;
  color: #fff;
}

.el-button--primary:hover {
  background: linear-gradient(135deg, #66b1ff, #409EFF); /* 按钮悬停渐变颜色 */
  border-color: #66b1ff;
}

@media (max-width: 768px) {
  .chart-container {
    padding: 20px;
  }

  .chart-title h2 {
    font-size: 28px;
  }

  .chart-title p {
    font-size: 16px;
  }

  .cost-info h2 {
    font-size: 24px;
  }

  .chart {
    height: 400px;
  }
}
</style>
